package com.sky.d_fork_jion;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

/**
 * ForkJoinPool的一个demo  统计数量
 * http://ifeve.com/fork-join-5/
 * @Author:hjt
 */
public class CountTask extends RecursiveTask<Integer>{

	private static final long serialVersionUID = 1L;

	private static final int THRESHOLD = 2;		//阀值
	
	private int start;
	
	private int end;
	
	public CountTask(int start, int end){
		this.start = start;
		this.end = end;
	}
	
	@Override
	protected Integer compute() {
		
		int sum = 0;
		
		//如果任务足够小就计算任务
		boolean canCompite = (end - start) <= THRESHOLD;
		if(canCompite){
			for(int i = start; i<= end; i++){
				sum += i;
			}
		} else {
			
			//通过递归的方式划分子任务处理
			
			//如果任务大于阀值，就分裂成两个子任务
			int middle = (start + end)/2;
			CountTask leftTask = new CountTask(start, middle);
			CountTask rightTask = new CountTask(middle + 1, end);
			
			//执行子任务
			leftTask.fork();
			rightTask.fork();
			
			//等待子任务执行完，并得到其结果
			int leftResult = leftTask.join();
			int rightResult = rightTask.join();
			
			//合并子任务
			sum = leftResult + rightResult;
			
		}
		
		return sum;
	}
	
	public static void main(String[] args) {
		ForkJoinPool forkJoinPool = new ForkJoinPool();
		
		//生成一个计算任务，负责计算1+2+3+4
		CountTask task = new CountTask(1, 4);
		//执行任务
		Future<Integer> result = forkJoinPool.submit(task);
		
		try {
			System.out.println("执行结果--->" + result.get());
		} catch (InterruptedException | ExecutionException e) {
			//被打断异常和执行中异常
			e.printStackTrace();
		}
		
		forkJoinPool.shutdown();
		
	}

}

